// models/User.js
const pool = require('../config/database');
const bcrypt = require('bcryptjs');

class User {
  // 创建用户
  static async create(userData) {
    const { phone, password, name, email, city, gender } = userData;
    
    // 加密密码
    const hashedPassword = await bcrypt.hash(password, 10);
    
    const [result] = await pool.execute(
      'INSERT INTO users (phone, password, name, email, city, gender) VALUES (?, ?, ?, ?, ?, ?)',
      [phone, hashedPassword, name, email, city, gender]
    );
    
    return result.insertId;
  }

  // 根据手机号查找用户
  static async findByPhone(phone) {
    const [rows] = await pool.execute(
      'SELECT * FROM users WHERE phone = ?',
      [phone]
    );
    
    return rows[0];
  }

  // 根据ID查找用户
  static async findById(id) {
    const [rows] = await pool.execute(
      'SELECT id, phone, name, avatar, email, city, gender, created_at FROM users WHERE id = ?',
      [id]
    );
    
    return rows[0];
  }

  // 更新用户信息
  static async update(id, updateData) {
    console.log('User.update 被调用, ID:', id, '数据:', updateData);
    
    const { name, email, city, gender, avatar } = updateData;
    
    // 构建动态更新字段
    const updateFields = [];
    const values = [];
    
    if (name !== undefined) {
      updateFields.push('name = ?');
      values.push(name);
    }
    if (email !== undefined) {
      updateFields.push('email = ?');
      values.push(email);
    }
    if (city !== undefined) {
      updateFields.push('city = ?');
      values.push(city);
    }
    if (gender !== undefined) {
      updateFields.push('gender = ?');
      values.push(gender);
    }
    if (avatar !== undefined) {
      updateFields.push('avatar = ?');
      values.push(avatar);
    }
    
    if (updateFields.length === 0) {
      console.log('没有要更新的字段');
      return false;
    }
    
    values.push(id);
    
    const sql = `UPDATE users SET ${updateFields.join(', ')} WHERE id = ?`;
    console.log('执行SQL:', sql);
    console.log('参数:', values);
    
    try {
      const [result] = await pool.execute(sql, values);
      console.log('数据库更新结果:', result);
      return result.affectedRows > 0;
    } catch (error) {
      console.error('数据库更新错误:', error);
      throw error;
    }
  }

  // 验证密码
  static async verifyPassword(plainPassword, hashedPassword) {
    return await bcrypt.compare(plainPassword, hashedPassword);
  }
}

// 确保正确导出
module.exports = User;